<template>
  <div>
    <div class="header-search-box shadow">
      <myForm
        :searchBox="{ span: 6 }"
        :span="6"
        :optionData="searchForm.optionData"
        :ruleForm="searchForm.data"
        :formData="searchForm.config"
        @reset="resetForm"
        @submitForm="getRiskList(true)"
      >
        <template v-slot:indexNameList>
          <el-select v-model="searchForm.data.indexName" filterable multiple placeholder="请选择">
            <el-option
              v-for="item in searchForm.optionData.indexData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </template>
      </myForm>
    </div>
    <div class="scene-main tab-scene-main">
      <div class="mul-btn">
        <el-button type="primary" @click="handleBatchOpt" :disabled="activeName != '0'" v-if="codeSessionSign"
          >批量操作</el-button
        >
      </div>
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane
          v-for="(item, index) in $store.state.dictionary[100700]"
          :key="index"
          :label="item.label"
          :name="item.value || 'all'"
        ></el-tab-pane>
      </el-tabs>
      <sec-table
        :loading="searchTable.loading"
        selection
        @selectionChange="selectionChange"
        :tableData="searchTable.rows"
        :tableCol="searchTable.cols"
        ref="secTabel"
      >
      </sec-table>

      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page.sync="currentPage"
        background
        :page-sizes="pageSizes"
        :page-size="pageSize"
        :layout="layout"
        :total="totalSize"
      >
      </el-pagination>
    </div>

    <el-dialog title="操作" :visible.sync="diaShow" width="50%">
      <div style="margin-bottom: 10px">
        <el-button
          :type="selectIndex == index ? 'primary' : ''"
          :disabled="item.disabled"
          @click="btnTab(item, index)"
          v-for="(item, index) in mulOperation"
          :key="index"
          >{{ item.title }}</el-button
        >
      </div>
      <myForm
        ref="mulOperation"
        :rules="mulForm.rules"
        :ruleForm="mulForm.ruleForm"
        :formData="mulForm.formData"
      ></myForm>
    </el-dialog>
  </div>
</template>

<script>
import myForm from "components/formValidate/myForm";
import secTable from "components/table/comTable";
import { paginationMixin } from "common/js/mixin";
import { config } from "@/textConfig";
import secDescriptions from "components/descriptions/myDescriptions";
import { riskSocApi, riskHoleStatusApi, riskListApi, riskMisreportApi, indexNameApi } from "api/controlApi";
import { cancelMisreportApi } from "api/api";
import { getCodeSession } from "@/utils";
import { assetsSubsystemCodeList } from "api/propertyManage";
export default {
  name: "riskManage",
  props: {},
  mixins: [paginationMixin],
  components: {
    myForm,
    secTable,
    secDescriptions,
  },
  data() {
    return {
      status: "",
      dateType: "",
      selectRows: [], //多选的行
      mulOpt: false, //是否是批量操作
      codeSessionSign: true, //权限控制
      activeName: "0",
      diaShow: false,
      selectIndex: 0,
      mulOperation: [
        { title: "同步漏洞平台", disabled: false },
        { title: "误报", disabled: false },
        { title: "人工忽略", disabled: false },
      ], //批量操作选项
      searchForm: {
        data: {
          riskName: "",
          indexName: "", // 指标名称
          domain: "",
          assetCode: [],
          dateType: "",
          statuses: [],
          itemScene: [],
          tempStatuses: [], //切换标签时缓存statuses数据
        },
        optionData: {
          dateType: this.$store.state.dictionary.dateType,
          indexData: "",
          statuses: this.$store.state.dictionary[100700].filter((item, index) => {
            return item.value != "";
          }),
          itemScene: this.$store.state.dictionary[101003],
          assetCode: [],
        },
        config: [
          {
            type: "text",
            label: "风险名称",
            prop: "riskName",
            placeholder: "请输入风险名称（风险ID）",
          },
          {
            type: "text",
            label: "域名",
            prop: "domain",
            placeholder: "请输入域名",
          },
          {
            type: "select",
            multiple: true,
            filterable: true,
            clearable: true,
            allowCreate: true,
            collapseTags: true,
            label: "appID",
            prop: "assetCode",
            placeholder: "请输入appID",
          },
          {
            type: "select",
            label: "指标来源",
            prop: "itemScene",
            multiple: true,
            placeholder: "请输入指标来源",
          },
          {
            type: "select",
            label: "风险来源",
            prop: "dateType",
            multiple: true,
          },
          {
            type: "slot",
            label: "指标名称",
            prop: "indexNameList",
          },
        ],
      },
      searchTable: {
        loading: false,
        cols: [
          { label: "风险ID", prop: "id", width: 80 },
          { label: "风险名称", prop: "riskName", width: 250 },
          { label: "风险类型", prop: "holeType", width: 150 },
          {
            label: "风险状态",
            prop: "status",
            width: 150,
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("100700", cellValue);
            },
          },
          {
            label: "风险等级",
            prop: "level",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("level", cellValue);
            },
          },
          { label: "风险描述", prop: "holeDetail", width: 300 },
          { label: "关联指标", prop: "itemName", width: 200 },
          { label: "关联资产", prop: "domain", width: 250 },
          {
            label: "风险来源",
            prop: "dateType",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("dateType", cellValue);
            },
          },
          { label: "创建时间", prop: "createTimeText", width: 150 },
          {
            label: "操作",
            prop: "operation",
            width: 220,
            children: [
              {
                label: "同步漏洞平台",
                hide: ({ row, column, $index }) => {
                  if (this.$common.isPerIgnore(row.status)) {
                    return true;
                  }
                  let arr = ["0"]; //风险状态码
                  return !arr.includes(row.status) || !getCodeSession();
                },
                click: ({ row, column, $index }) => {
                  this.mulForm.ruleForm.remark = "";
                  this.mulOpt = false;
                  this.dateType = row.dateType;
                  this.diaOpeBtnNoDis("同步漏洞平台");
                  this.selectIndex = 0;
                  this.diaShow = true;
                  this.selectRisk = row;
                },
              },
              {
                // label: "误报",
                labelFunc: ({ row }) => {
                  //审计任务:datasec_report
                  //监控任务:datasec_monitor
                  if (row.dateType == "datasec_report" || row.dateType == "subsystem_report") {
                    return "人工忽略";
                  } else if (row.dateType == "datasec_monitor" || row.dateType == "subsystem_monitor") {
                    return "误报";
                  }
                },
                hide: ({ row, column, $index }) => {
                  if (this.$common.isPerIgnore(row.status)) {
                    return true;
                  }
                  let arr = ["0"];
                  return !arr.includes(row.status) || !getCodeSession();
                },
                click: ({ row, column, $index }) => {
                  this.mulOpt = false;
                  let type =
                    row.dateType == "datasec_report" || row.dateType == "subsystem_report" ? "人工忽略" : "误报";
                  this.selectIndex = row.dateType == "datasec_report" || row.dateType == "subsystem_report" ? 2 : 1;
                  this.status = row.dateType == "datasec_report" || row.dateType == "subsystem_report" ? "121" : "12";
                  this.diaOpeBtnNoDis([type]); //误报或者人工忽略按钮失效逻辑
                  this.diaShow = true;
                  this.resetDia();
                  this.selectRisk = row;
                },
              },
              {
                label: "详情",
                click: ({ row, column, $index }) => {
                  this.$router.push({
                    path: "/control/risk/detail",
                    query: { riskId: row.id, assetId: row.assetId, code: row.code, assetType: row.assetType },
                  });
                },
              },
              {
                label: "取消误报",
                hide: ({ row, column, $index }) => {
                  let arr = ["12"];
                  return !arr.includes(row.status) || !getCodeSession();
                },
                click: ({ row, column, $index }) => {
                  this.$prompt("备注：", "取消误报", {
                    // type: "warning",
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    // maxlength: 200,
                    inputType: "textarea",
                    inputPattern: /\S/,
                    inputErrorMessage: "请输入",
                  }).then(({ value }) => {
                    console.log(value);
                    if (value.length > 200) {
                      this.message.warning({ message: "不能超过200字" });
                      return;
                    }
                    cancelMisreportApi({ ids: [row.id], remark: value }).then((res) => {
                      let state = this.message.state(res);
                      if (!state) return;
                      this.getRiskList();
                    });
                  });
                },
              },
              {
                hide: ({ row, column, $index }) => {
                  if (this.$common.isPerIgnore(row.status)) {
                    return true;
                  }
                  let arr = ["1-4", "5"];
                  return !arr.includes(row.status) || !getCodeSession();
                },
                label: "同步工单状态",
                click: ({ row, column, $index }) => {
                  riskHoleStatusApi({ riskId: row.id, anquanId: row.anquanId }).then((res) => {
                    this.message.success({ message: res.msg });
                    this.getRiskList();
                  });
                },
              },
              {
                hide: ({ row, column, $index }) => {
                  if (this.$common.isPerIgnore(row.status)) {
                    return true;
                  }
                  let arr = ["0", "12"];
                  return arr.includes(row.status);
                },
                label: "工单详情",
                click: ({ row, column, $index }) => {
                  let domain = "http://anquan.didichuxing.com"; //测试的地址是http://anquan-test.didichuxing.com
                  window.open(`${domain}/project/portals/pages/hole-detail.html?id=${row.anquanId}`);
                },
              },
            ],
          },
        ],
        rows: [],
      },
      mulForm: {
        ruleForm: {
          remark: "",
        },
        formData: [
          {
            type: "textarea",
            label: "备注",
            rows: 4,
            prop: "remark",
          },
          {
            type: "operation",
            style: { "text-align": "right" },
            children: [
              {
                label: "取 消",
                click: () => {
                  this.diaShow = false;
                },
              },
              {
                label: "确 认",
                type: "primary",
                click: () => {
                  if (this.$refs.mulOperation.submitForm()) {
                    //selectIndex:0 是同步漏洞平台 1是误报
                    if (this.selectIndex == 1 || this.selectIndex == 2) {
                      this.errReportConfirm();
                    } else {
                      this.asyncHoleConfirm();
                    }
                  }
                },
              },
            ],
          },
        ],
        rules: {
          remark: [{ required: true, message: config.input, trigger: "blur" }],
        },
      },
    };
  },
  computed: {},
  mounted() {
    //链接跳转后直接展示筛选结果
    let { domain, assetCode, statuses, rechecked, riskId } = this.$route.query;
    statuses && (statuses = JSON.parse(statuses));
    domain && ((this.activeName = "all"), this.processStatuses());
    assetCode && ((this.activeName = "all"), this.processStatuses());
    rechecked && (this.activeName = "9");
    this.searchForm.data = { ...this.searchForm.data, domain, statuses, rechecked, riskId };
    assetCode &&
      (this.$set(this.searchForm.data, "assetCode", []), //重新添加一个assetCode字段
      (this.searchForm.optionData.assetCode = [{ label: assetCode, value: assetCode }]),
      this.searchForm.data["assetCode"].push(assetCode));
    this.codeSessionSign = getCodeSession();
    this.getRiskList("mounted");
    this.getSelectIndexName();
    // 获取appID
    assetsSubsystemCodeList({ assetType: "SSO" }).then((res) => {
      this.searchForm.optionData.assetCode = res.data.map((item) => {
        return { label: item, value: item };
      });
    });
  },
  methods: {
    resetForm() {
      this.searchForm.data.tempStatuses = [];
      this.searchForm.data.statuses = [];
      this.getRiskList(true);
    },
    getRiskList(paginationReset) {
      console.log(this.searchForm.data);
      //不为页面首次加载时，去除隐藏筛选参数影响
      if (paginationReset != "mounted") {
        this.searchForm.data = { ...this.searchForm.data, rechecked: "", riskId: "" };
      }
      //解决点击搜索或者重置的时候 改成第一页
      if (paginationReset) {
        this.paginationReset();
      }
      this.searchTable.loading = true;
      riskListApi({
        riskName: this.searchForm.data.riskName,
        dateType: this.searchForm.data.dateType,
        domain: this.searchForm.data.domain,
        status: this.activeName === "all" ? "" : this.activeName,
        statuses: this.searchForm.data.statuses,
        rechecked: this.searchForm.data.rechecked,
        riskId: this.searchForm.data.riskId,
        assetCode: this.searchForm.data.assetCode,
        assetType: "SSO",
        itemScene: this.searchForm.data.itemScene,
        //todo
        codeList: this.searchForm.data.indexName,
        pageNum: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        console.log(res);
        this.totalSize = res.count;
        this.searchTable.loading = false;
        this.searchTable.rows = res.data;
      });
    },
    /**
     * @函数功能:设置误报
     * @参数输入:
     * @函数返回:
     */
    errReportConfirm() {
      riskMisreportApi({ ids: this.getSelectRowIds(), status: this.status, remark: this.mulForm.ruleForm.remark }).then(
        (res) => {
          this.diaShow = false;
          this.message.success({ message: res.msg });
          this.getRiskList();
        },
      );
    },
    /**
     * @函数功能:同步漏洞平台 弹框的确认按钮
     * @参数输入:
     * @函数返回:
     */
    asyncHoleConfirm() {
      riskSocApi({ riskIds: this.getSelectRowIds(), dateType: this.dateType }).then((res) => {
        this.diaShow = false;
        this.message.success({ message: res.msg });
        this.getRiskList();
      });
    },
    getSelectRowIds() {
      let ids = [];
      if (this.mulOpt) {
        ids = this.selectRows.map((item) => item.id);
      } else {
        ids.push(this.selectRisk.id);
      }
      return ids;
    },
    // 获取指标名称选项表
    getSelectIndexName() {
      indexNameApi().then((res) => {
        this.searchForm.optionData.indexData = res.data;
      });
    },
    allElementsEqual(arr) {
      // 如果数组为空，则返回 true
      if (arr.length === 0) {
        return true;
      }
      // 使用数组的第一个元素作为比较基准
      const firstElem = arr[0];
      // 使用 every 方法遍历数组并检查每个元素是否与基准相同
      const allEqual = arr.every((elem) => elem === firstElem);
      // 返回结果
      return allEqual;
    },
    /**
     * @函数功能:批量操作
     * @参数输入:
     * @函数返回:
     */
    handleBatchOpt() {
      if (this.selectRows.length <= 0) {
        this.message.warning({ message: "请选择" });
        return;
      }
      if (this.diaOpeBtnHandle()) {
        this.message.warning({ message: "不能同时选择风险来源不同的任务" });
        return;
      }
      this.mulOpt = true;
      // this.selectIndex = 0;
      this.diaShow = true;
      this.resetDia();
    },
    /**
     * @函数功能:批量操作 按钮选中切换
     * @参数输入:
     * @函数返回:
     */
    btnTab(item, index) {
      this.selectIndex = index;
    },
    selectionChange(selectRows) {
      this.selectRows = selectRows;
      this.diaOpeBtnHandle();
    },
    diaOpeBtnHandle() {
      let dateType = [];
      this.selectRows.forEach((item) => {
        dateType.push(item.dateType);
      });
      //审计任务:datasec_report
      //监控任务:datasec_monitor
      if (!this.allElementsEqual(dateType)) {
        // this.diaOpeBtnNoDis(["同步漏洞平台"]);
        return true;
        // this.selectIndex = 0;
      } else if (dateType.includes("datasec_report")) {
        this.diaOpeBtnNoDis(["人工忽略", "同步漏洞平台"]);
        this.dateType = "datasec_report";
        this.selectIndex = 2;
      } else if (dateType.includes("datasec_monitor")) {
        this.diaOpeBtnNoDis(["误报", "同步漏洞平台"]);
        this.dateType = "datasec_monitor";
        this.selectIndex = 1;
      } else if (dateType.includes("subsystem_report")) {
        this.diaOpeBtnNoDis(["人工忽略", "同步漏洞平台"]);
        this.dateType = "subsystem_report";
        this.selectIndex = 2;
      } else if (dateType.includes("subsystem_monitor")) {
        this.diaOpeBtnNoDis(["误报", "同步漏洞平台"]);
        this.dateType = "subsystem_monitor";
        this.selectIndex = 1;
      }
    },
    resetDia() {
      this.$nextTick(() => {
        this.$refs.mulOperation.resetForm();
        this.mulForm.ruleForm.remark = "";
      });
    },
    //弹框按钮置灰处理 传入的值为不置灰的的
    //types:Array ["误报"]
    diaOpeBtnNoDis(types) {
      this.mulOperation.forEach((item) => {
        item.disabled = types.includes(item.title) ? false : true;
      });
    },
    processStatuses() {
      // console.log(this.activeName);
      if (this.activeName != "all") {
        this.searchForm.data.statuses != [] && (this.searchForm.data.tempStatuses = this.searchForm.data.statuses);
        this.searchForm.data.statuses = [];
        this.searchForm.config = this.searchForm.config.filter((item) => {
          console.log(item.prop);
          return item.prop != "statuses";
        });
      } else {
        if (
          !this.searchForm.config.some((item) => {
            return item.prop == "statuses";
          })
        ) {
          this.searchForm.data.statuses = this.searchForm.data.tempStatuses;
          this.searchForm.config.push({
            type: "select",
            label: "风险状态",
            prop: "statuses",
            multiple: true,
            span: 20,
          });
        }
      }
      // console.log(this.searchForm.data.tempStatuses, this.searchForm.data.statuses);
    },
    tabClick(e) {
      this.processStatuses();
      this.getRiskList();
    },
    sizeChange(val) {
      this.pageSize = val;
      this.getRiskList();
    },
    currentChange(val) {
      this.page = val;
      this.getRiskList();
    },
  },
  watch: {},
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
</style>
